package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Author: zhang xing jian
 * Date: 2025/10/10 15:48
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {

        // 获取用户输入的验证码和存在redis中验证码的key
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();

        // 根据key获取redis中的验证码
        String redisCode = redisTemplate.opsForValue().get("user:validatecode:" + codeKey);

        // 验证码校验
        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode, captcha)) {
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        // 1. 获取用户名
        String username = loginDto.getUserName();

        // 2. 根据用户查询数据库信息
        SysUser sysUser = sysUserMapper.findByUsername(username);

        // 3.判断用户是否存在
        if(sysUser == null) {
//            throw new RuntimeException("用户不存在");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 4.如果用户存在
        // 5.密码校验
        String db_password = sysUser.getPassword();
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        if (!input_password.equals(db_password)) {
//            throw new RuntimeException("用户名或者密码错误");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 6.如果密码一致，生成令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(sysUser),7, TimeUnit.DAYS);
        redisTemplate.delete("user:validatecode:" + codeKey);

        // 7.返回结果
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        return JSON.parseObject(userJson, SysUser.class);
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:" + token);
    }
}
